/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-12-05 10:59:48
 * @LastEditors: Clark
 * @LastEditTime: 2023-12-29 13:47:34
 * @Description: file content
 */
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QTimer>
#include <QDebug>
#include <QDateTime>

#define TODAY "Today count: "
#define STAGE "This stage count: "

#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle("Pomodoro Work");
    setWindowIcon(QIcon(":/res/jobs1.ico"));

    tomatoClock_ = std::make_shared<TomatoClock>("infoFile", "dataFile");
    tomatoClock_->init();

    stageCount = 0;
    todayCount = tomatoClock_->get_clock_count();
    update_count();

    displayTime = new QTimer(this);
    connect(displayTime, &QTimer::timeout, this, &MainWindow::dealTimeout);

    thread = new MyThread(this);
    connect(thread, &MyThread::isDone, this, &MainWindow::dealDone);

    connect(thread, &MyThread::destroyed, this, &MainWindow::stopThread);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::update_count()
{
    QString strTodayCount = QString("%1%2").arg(TODAY).arg(todayCount);
    ui->today->setText(strTodayCount);

    QString strStageCount = QString("%1%2").arg(STAGE).arg(stageCount);
    ui->stage->setText(strStageCount);
}

void MainWindow::dealTimeout()
{
    ui->lcdNumber->display(count);
    count++;
}

void MainWindow::dealDone()
{
    stageCount++;
    todayCount++;
    update_count();

    displayTime->stop();
    this->activateWindow();
    this->raise();
    qDebug()<<"Show the window most front";
}

void MainWindow::stopThread()
{
    thread->quit();
    thread->wait();
}

void MainWindow::on_start_clicked()
{
    if (displayTime->isActive() == false)
    {
        displayTime->start(1000);
        thread->start();
        tomatoClock_->add_clock();
    }

    // 非常复杂的函数处理，耗时较长
    //QThread::sleep(5);
    // 处理完数据后，关闭定时器
    //displayTime->stop();
    //qDebug() << "over";

    // 启动线程，处理数据
    count = 0;
}

void MainWindow::on_clearStage_clicked()
{
    stageCount = 0;
    QString strStageCount = QString("%1%2").arg(STAGE).arg(stageCount);
    ui->stage->setText(strStageCount);
}
